<template>
  <div class="shadow-ai-chat-input rounded-lg flex justify-between">
    <div
      class="w-full flex-col justify-between p-2 relative flex items-center rounded-lg shadow-sm transition-all duration-300 focus-within:ring-2 focus-within:ring-opacity-25"
      :style="{
        backgroundColor: 'var(--color-ai-chat-input-bg)',
        boxShadow: 'var(--shadow-ai-chat-input)',
      }">
      <UIChatPlanel :message="responseMessage" />
      <div class="flex flex-col w-full">
        <div class="flex w-full justify-between">
          <div class="flex gap-1">
            <UISelect :render-label="(item: selectAIOptions) => RenderLabel(item, AIBarChatNowSelectModel!)"
              :style="{ width: selectModelWidth + 'px' }" size="tiny" placeholder="选择模型"
              :value="AIBarChatNowSelectModel?.id || undefined" no-style :options="modalSenderOptions"
              @update:value="setAiBarChatNowSelectModel" filterable :consistent-menu-width="false">
            </UISelect>
            <UIButton @click="() => replaceMessage(responseMessage)"
              v-if="responseMessage && getALlSpanActiveTxt() && !loading" size="tiny" quaternary>替换
            </UIButton>
            <UIButton @click="() => copyMessage(responseMessage)"
              v-if="responseMessage && getALlSpanActiveTxt() && !loading" size="tiny" quaternary>复制
            </UIButton>
          </div>
          <div class="flex items-center">
            <UIText v-if="props.closeable" class="text-[10px] cursor-pointer" @click="closeAIBar">Esc to close</UIText>
            <UIButton v-if="props.closeable" @click="closeAIBar" size="small" icon-name="Close" no-style circle>
            </UIButton>
          </div>
        </div>
        <div class="flex pt-2">
          <template v-if="loading">
            <LoadingDots class="flex-1" />
          </template>
          <template v-else>
            <UIInput class="flex-1" size="tiny" no-style ref="AIInputRef" type="text" v-model:value="message"
              placeholder="输入你想问的..." @keydown.enter="sendMessage" />
          </template>
          <UIButton size="small" :disabled="!message || !AIBarChatNowSelectModel"
            :icon-name="loading ? 'StopFilledAlt' : 'SendAltFilled'" :class="{
              'hover:-translate-y-0 active:translate-y-0':
                message && AIBarChatNowSelectModel,
            }" class="transition-all duration-200 cursor-pointer translate-y-0.5" no-style circle @click="sendMessage">
          </UIButton>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { storeToRefs } from "pinia";
import UIInput from "@/components/UI/Input/index.vue";
import LoadingDots from "../LoadingDots/index.vue";
import { Method } from "alova";
const props = defineProps<{ closeable?: boolean }>()
const message = ref("");
const responseMessage = ref("");
const { modalSenderOptions, AIBarChatNowSelectModel } =
  storeToRefs(settingsStore());
const { setAiBarChatNowSelectModel, getProviderByName } = settingsStore();

const {
  setAiSelectionBarShow,
  setAiSelectionBarPositionHandler,
} = useAISelectionBar();
const { sendChatMessage, loading, getALlSpanActiveTxt, replaceMessage, copyMessage } = useEditorAgent();


const closeAIBar = () => {
  setAiSelectionBarShow(false);
};
const methodRef = ref<Method>()
const sendMessage = async (e?: Event) => {
  if (loading.value) {
    loading.value = false;
    methodRef.value && methodRef.value.abort();
    return
  }
  e?.stopPropagation();
  const msg = message.value.trim();
  const txt = getALlSpanActiveTxt();
  responseMessage.value = "";
  const toolCall: tool_call[] = [];
  const method = sendChatMessage(
    (txt
      ? `你是一个写作助手需要根据我的要求对content标签的内容进行处理。请仅仅回复处理后的内容。
    <content>
    ${txt}
    </content>
    以下是对内容的处理要求：`
      : "") + msg,
    { tools: getAllFunctionCallingTools() },
    (isDone: boolean, content?: string, tool_calls?: tool_call[]) => {
      tool_calls && toolCall.push(...tool_calls);
      content && (responseMessage.value += content);
      setAiSelectionBarPositionHandler();
      isDone && CallingFunction(toolCall);
    }
  );
  const provider = getProviderByName(AIBarChatNowSelectModel.value!.provider)!;
  method.baseURL = provider.API_URL
  method.config.headers.Authorization = `Bearer ${provider.API_KEY}`;
  methodRef.value = method;
};
const selectModelWidth = ref(100);
watchEffect(() => {
  if (AIBarChatNowSelectModel.value?.id) {
    const txt = AIBarChatNowSelectModel.value.name
      || AIBarChatNowSelectModel.value.id?.replace("models/", "")
    const textWidth = measureTextTarget(txt, 15).width
    selectModelWidth.value = Math.min(textWidth + (textWidth < 50 ? 40 : 20), 350);
  }
});
const RenderLabel = (item: selectAIOptions, model: ModelExtend) => {
  if (item.disabled) {
    return item.label
  }
  if ((item.value as selectAIOptionsValue).model) {
    return (
      (item.value as selectAIOptionsValue).model.name?.replace("models/", "") ||
      (item.value as selectAIOptionsValue).model.id?.replace("models/", "")
    );
  }

  return model.name?.replace("models/", "") || model.id?.replace("models/", "");
};
const AIInputRef = useTemplateRef<InstanceType<typeof UIInput>>("AIInputRef");
const onEscape = (e: KeyboardEvent) => {
  if (e.key === "Escape") {
    setAiSelectionBarShow(false);
  }
};
onMounted(() => {
  AIInputRef.value?.focus();
  props.closeable && document.addEventListener("keydown", onEscape);
});
onBeforeMount(() => {
  props.closeable && document.removeEventListener("keydown", onEscape);
});
</script>

<style scoped></style>
